#include"Sequence.h"
void SeqListInit(SeqList* ps)
{
    assert(ps);
    ps->a = NULL;
    ps->size = 0;
    ps->capacity = 0;
}
void SeqListDestory(SeqList* ps)
{
    free(ps->a);
    ps->a = NULL;
    ps->size = ps->capacity = 0;
}
void CheckCapacity(SeqList* ps)
{
    if (ps->size == ps->capacity) //判断容量是否满了
    {
        size_t newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
        DateType* tmp = (DateType*)realloc(ps->a, sizeof(DateType) * newcapacity);//两倍扩容
        if (tmp == NULL)
        {
            perror("malloc:");
            exit(1);
        }
        ps->a = tmp;
        ps->capacity = newcapacity;
    }
}

//凡是插入都需要检查容量 是否需要扩容
//凡是删除元素需要判断顺序表是否为空
void SeqListPrint(SeqList* ps)
{
    for (int i = 0; i < ps->size; i++)
    {
        printf("ps->a[%d]:%d\n", i, ps->a[i]);
    }
    printf("\n");
}
void SeqListPushBack(SeqList* ps, DateType x)
{
    CheckCapacity(ps);
    ps->a[ps->size++] = x;
}
void SeqListPushFront(SeqList* ps, DateType x)
{
    CheckCapacity(ps);
    for (int i = ps->size - 1; i >= 0; i--)
        ps->a[i + 1] = ps->a[i];
    ps->size++;
    ps->a[0] = x;
}
void SeqListPopFront(SeqList* ps)
{
    if (ps->size == 0)
    {
        printf("顺序表为空,请先插入元素\n");
        exit(1);
    }
    for (int i = 1; i < ps->size; i++)
        ps->a[i - 1] = ps->a[i];
    ps->size--;
}
void SeqListPopBack(SeqList* ps)
{
    if (ps->size == 0)
    {
        printf("顺序表为空,请先插入元素\n");
        exit(1);
    }
    ps->size--;
}


int SeqListFind(SeqList* ps, DateType x)
{
    for (int i = 0; i < ps->size; i++)
    {
        if (ps->a[i] == x)
            return i;
    }
    return -1;
}
// 顺序表在pos位置插入x
void SeqListInsert(SeqList* ps, size_t pos, DateType x)
{
    assert(pos >= 0 && pos <= ps->size);
    CheckCapacity(ps);
    /*坑点,err写法
    //当在0位置进行插入的时候会出现死循环！！
    //原因：因为pos是无符号类型，i虽然是整形但是和无符号类型进行比较的时候会发生整型提升为无符号类型
    //i变为无符号类型->i>=0 ==>i>=pos恒成立
    // for (int i = ps->size-1; i >= pos; i--)
    // {
    //     ps->a[i+1] = ps->a[i];
    // }
    */
    //正确写法：i和pos进行比较不能取相等  防止出现pos位置取0的情况
    for (int i = ps->size; i > pos; i--)
        ps->a[i] = ps->a[i-1];
    ps->size++;
    ps->a[pos] = x;
}
// 顺序表删除pos位置的值
void SeqListErase(SeqList* ps, size_t pos)
{
    assert(ps->size >= 1);
    assert(pos >= 0 && pos < ps->size);
    for (int i = pos; i < ps->size; i++)
    {
        ps->a[i] = ps->a[i + 1];
    }
    ps->size--;
}
